<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <!--<el-form-item label="通知单编号" prop="tongzhiNo">
        <el-input v-model="queryParams.tongzhiNo" placeholder="请输入通知单编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>-->
      <el-form-item label="发货编码" prop="nos">
        <el-input v-model="queryParams.nos" placeholder="请输入发货编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号" prop="projectNos">
        <el-input v-model="queryParams.projectNos" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发货日期" prop="fahuoDate">
        <el-date-picker clearable v-model="queryParams.fahuoDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择发货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="交货日期">
        <el-date-picker v-model="dateRange" style="display: flex;" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="联系人" prop="linkman">
        <el-input v-model="queryParams.linkman" placeholder="请输入联系人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="linktel">
        <el-input v-model="queryParams.linktel" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入收货地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发运方式" prop="shipType">
        <el-input v-model="queryParams.shipType" placeholder="请输入发运方式" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户" prop="models">
        <el-select v-model="queryParams.kehuId" placeholder="请选择客户" filterable 
                   clearable style="width: 100%">
          <el-option v-for="dict in dict.type.goods_customer" :data="dict.raw" ref="myselectCustomerForPrj"
                     :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="发货状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
          <el-option v-for="dict in dict.type.yifahuo_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['develop:LvYifahuo:add']">新增发货单
        </el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="export2Excel">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
      @sort-change="handleSortChange">
      <el-table-column sortable label="发货编码" align="center" prop="nos" show-overflow-tooltip />
      <el-table-column sortable label="订单编号" align="center" prop="projectNos" />
      <el-table-column sortable label="业务员" align="center" prop="saleman" />
      <el-table-column sortable label="发货日期" align="center" prop="fahuoDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fahuoDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="交货日期" align="center" prop="jiaohuoDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jiaohuoDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="联系人" align="center" prop="linkman" />
      <el-table-column sortable label="联系电话" align="center" prop="linktel" />
      <el-table-column sortable label="发货地址" align="center" prop="address" show-overflow-tooltip />
      <el-table-column sortable label="发货状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yifahuo_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column sortable label="客户名称" align="center" prop="kehuName" show-overflow-tooltip />
       <el-table-column sortable label="发货金额" align="center" prop="taxAllmoeny" show-overflow-tooltip />
      <!--      <el-table-column label="过磅重量" align="center" prop="guobangDun"/>-->
      <!--      <el-table-column align="center" label="过磅单" prop="guobangdan" show-overflow-tooltip>-->
      <!--        <template slot-scope="scope">-->
      <!--          <file-upload-show :value="scope.row.guobangdan"></file-upload-show>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column align="center" label="到货回执" prop="daohuoFile" show-overflow-tooltip>
        <template slot-scope="scope">
          <file-upload-show :value="scope.row.daohuoFile"></file-upload-show>
        </template>
      </el-table-column>
      <el-table-column label="发运方式" align="center" prop="shipType" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column sortable label="制单人" align="center" prop="createBy"/>
      <el-table-column label="操作" align="center" prop="operation" class-name="small-padding fixed-width" fixed="right"
        width="290">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-document" @click="xiangqing(scope.row)">发货单详情
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-printer" @click="printDetail(scope.row)">发货单打印
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status === '3' || scope.row.status === '0'"
            @click="modify(scope.row)">修改发货单
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-close" v-hasPermi="['develop:LvYifahuo:qishen']"
            @click="bohui(scope.row)" v-if="scope.row.status === '2'">弃审
          </el-button>
          <el-popconfirm :title="`确认审核通过当前数据项？`" @confirm="tongyi(scope.row)"
            v-show="scope.row.status === '3' || scope.row.status === '0'" style="margin-left: 10px;">
            <el-button slot="reference" v-hasPermi="['develop:LvYifahuo:tongguo']" size="mini" type="text"
              icon="el-icon-check">
              发货确认
            </el-button>
          </el-popconfirm>
          <el-button size="mini" type="text" icon="el-icon-attract" @click="guobangdan(scope.row)">过磅单</el-button>
          <el-button size="mini" type="text" icon="el-icon-set-up"
            v-if="scope.row.status === '2' || scope.row.status === '4'" @click="daohuohuizhi(scope.row)">到货回执
          </el-button>

          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row)" style="margin-left: 10px;"
            v-show="scope.row.status !== '4' && scope.row.status !== '6' ">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
              v-hasPermi="['develop:LvYifahuo:remove']">删除
            </el-button>
          </el-popconfirm>

          <el-popconfirm :title="`确认确认当前数据项？`" @confirm="handleFinanceConfirm(scope.row)" style="margin-left: 10px;"
                         v-show="scope.row.status === '4'">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-bank-card"
                       v-hasPermi="['develop:LvYifahuo:financeConfirm']">财务确认
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <yiFahuo-list ref="fahuomingxiList" @ok="getList"></yiFahuo-list>
    <lvFahuoBohui-form ref="modifyfahuomingxi" @ok="getList"></lvFahuoBohui-form>
    <lvYifahuo-form ref="form" @ok="getList"></lvYifahuo-form>
    <lv-fahuo-choose-form ref="chooseForm" @ok="getList"></lv-fahuo-choose-form>
    <yifahuo-guobangdan ref="guobangdanForm" @ok="getList"></yifahuo-guobangdan>
    <yifahuo-huizhidan ref="daohuihuizhiForm" @ok="getList"></yifahuo-huizhidan>
    <lv-yifahuomingxi-list-module ref="yifahuoDetail"></lv-yifahuomingxi-list-module>
  </div>
</template>

<script>
import {
  deleteAction,
  getAction
} from '@/api/manage'
// 引入 XLSX 和 FileSaver 库
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import LvYifahuoForm from '@/views/develop/lvYifahuo/module/LvYifahuoForm'
import YiFahuoList from '@/views/develop/lvYifahuomingxi/YiFahuoList'
import LvFahuoBohuiForm from '@/views/develop/lvYifahuomingxi/module/LvFahuoBohuiForm'
import YifahuoGuobangdan from '@/views/develop/lvYifahuo/module/YifahuoGuobangdan'
import YifahuoHuizhidan from '@/views/develop/lvYifahuo/module/YifahuoHuizhidan'
import {
  list
} from "@/api/develop/lvYifahuo";
import LvFahuoChooseForm from "@/views/develop/lvYifahuo/module/LvFahuoChooseForm.vue";
import FileUploadShow from "@/components/FileUpload/FileUploadShow.vue";
import LvYifahuomingxiListModule from "@/views/develop/lvYifahuomingxi/module/LvYifahuomingxiListModule.vue";


export default {
  name: "LvYifahuoList",
  dicts: ['yifahuo_status','goods_customer'],
  components: {
    LvYifahuomingxiListModule,
    FileUploadShow,
    LvFahuoChooseForm,
    LvYifahuoForm,
    YiFahuoList,
    LvFahuoBohuiForm,
    YifahuoGuobangdan,
    YifahuoHuizhidan,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发货单表格数据
      dataList: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nos: null,
        projectNos: null,
        name: null,
        fahuoDate: null,
        jiaohuoDate: null,
        linkman: null,
        linktel: null,
        address: null,
        status: null,
        jingli: null,
        kehuId: null,
        kehuName: null,
        taxNo: null,
        taxCode: null,
        taxDate: null,
        taxMoney: null,
        taxShengyu: null,
        taxAllmoeny: null,
        allMoney: null,
        shengyu: null,
        yihui: null,
        daohuoDate: null,
        daohuoFile: null,
        tongzhiId: null,
        tongzhiNo: null,
        shipType: null,
        orderByColumn: "nos",
        isAsc: "descending"
      },
      url: {
        list: '/lvYifahuo/lvYifahuo/list',
        shenhetongguo: '/lvYifahuo/lvYifahuo/shenhetongguo/',
        export: '/lvYifahuo/lvYifahuo/export',
        remove: '/lvYifahuo/lvYifahuo/remove/',
        tishenCaiwu: '/lvYifahuo/lvYifahuo/tishenCaiwu/',
        financeConfirm: '/lvYifahuo/lvYifahuo/financeConfirm/',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
    //window.addEventListener('resize', this.getTableHeight);
  },
  /*destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },*/
  methods: {
    export2Excel() {
      const table = this.$refs.table;
      const columns = (table.$slots.default || []).filter(vnode => vnode.componentOptions?.tag === 'el-table-column');
      const exportFields = columns
        .map(vnode => {
          const props = vnode.componentOptions.propsData;
          return {
            prop: props.prop,
            label: props.label
          };
        })
        .filter(col => !['operation', 'handle', 'actions', 'index'].includes(col.prop)); // 过滤操作列

      // 定义字段与字典的映射关系
      const dictMap = {
        status: this.dict.type.yifahuo_status,       // 发货状态
      };

      // 构建并转换数据
      const exportData = this.dataList.map(item => {
        const row = {};
        exportFields.forEach(col => {
          const value = item[col.prop];
          // 如果该字段有字典映射，则使用 dictTag 的方式转换
          if (dictMap[col.prop]) {
            const matched = dictMap[col.prop].find(d => d.value === value);
            row[col.label] = matched ? matched.label : value;
          } else {
            // 如果是 daohuoFile 字段，添加请求地址前缀
            if (col.prop === 'daohuoFile') {
              row[col.label] = value ? `https://luneng.shandongwanhe.com:8013/prod-api${value}` : '';
            } else {
              row[col.label] = value;
            }
          }
        });
        return row;
      });

      const worksheet = XLSX.utils.json_to_sheet(exportData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      const wbout = XLSX.write(workbook, { bookType: 'xlsx', bookSST: true, type: 'array' });
      try {
        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '发货单列表.xlsx');
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e, wbout);
      }
    },
    guobangdan(row) {
      this.$refs.guobangdanForm.showGuobangdan(row);
    },
    daohuohuizhi(row) {
      if (row.status == 2 || row.status == 4) {
        this.$refs.daohuihuizhiForm.daohuohuizhiShow(row);
      } else {
        this.$modal.msgError("发货单审核中，请先完成审核");
      }
    },
    modify(row) {
      // this.$refs.modifyfahuomingxi.showModifyMingxi(row);
      this.$refs.chooseForm.handleUpdate(row);
    },
    printDetail(row) {
      this.$refs.fahuomingxiList.showMingxi(row);
    },


    xiangqing(row) {
      this.$refs.yifahuoDetail.showMingxi(row);
    },
    /** 查询发货单列表 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.chooseForm.handleAdd();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      deleteAction(this.url.remove, id).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功！");
      }).catch(() => {
      });
    },
    bohui(row) {
      this.$refs.form.handleUpdate(row);
    },
    tongyi(row) {
      const id = row.id;
      deleteAction(this.url.shenhetongguo, id).then(response => {
        this.getList();
        this.$modal.msgSuccess("审核通过！");
      }).catch(() => {
      });
    },
    tishenCaiwu(row) {
      const id = row.id;
      deleteAction(this.url.tishenCaiwu, id).then(response => {
        this.getList();
        this.$modal.msgSuccess("提交审核完成！");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(this.url.export, {
        ...this.queryParams
      }, `lvYifahuo_${new Date().getTime()}.xlsx`)
    },


    handleFinanceConfirm(row){
      getAction(this.url.financeConfirm+row.id,{}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      }).catch(() => {
      })
    }






  }
};
</script>
